package com.ruoyi.web.controller.smtdashboard;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.handler.AbstractRowWriteHandler;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.smtdashboard.domain.entity.QueryParams;
import com.ruoyi.smtdashboard.domain.entity.Smtdashboard;
import com.ruoyi.smtdashboard.service.SmtTableService;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import static com.ruoyi.common.core.domain.AjaxResult.error;
import static com.ruoyi.common.core.domain.AjaxResult.success;

@RestController
@RequestMapping("/dashboard")
public class SMTdashboardController {

    @Autowired
    SmtTableService smtTableService;

    QueryParams queryParams;

    @PostMapping("/querytable")
    public PageInfo<Smtdashboard> querytable(@Validated @RequestBody QueryParams queryParams){
        this.queryParams=queryParams;
        return smtTableService.qreuySmtTable(queryParams,true);
    }

    @PostMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        // 1. Set response headers
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        String fileName = URLEncoder.encode("SMTDashboard基础数据", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        // 2. Get data
        List<Smtdashboard> dataList = smtTableService.qreuySmtTable(queryParams,false).getList();

        // 3. Create Excel writer with custom handler
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), Smtdashboard.class)
                .registerWriteHandler(new AbstractRowWriteHandler() {
                    @Override
                    public void afterRowDispose(WriteSheetHolder writeSheetHolder,
                                                WriteTableHolder writeTableHolder,
                                                Row row,
                                                Integer relativeRowIndex,
                                                Boolean isHead) {
                        // Add timestamp after last data row
                        if (!isHead && relativeRowIndex != null && relativeRowIndex == dataList.size() - 1) {
                            Sheet sheet = writeSheetHolder.getSheet();
                            int lastRowNum = sheet.getLastRowNum();

                            // 创建当前时间
                            Row timeRow = sheet.createRow(lastRowNum + 1);
                            String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                            timeRow.createCell(0).setCellValue("导出时间:"+format);
                            // Merge cells if needed (columns 0-7)
                            sheet.addMergedRegion(new CellRangeAddress(
                                    lastRowNum + 1, // first row
                                    lastRowNum + 1, // last row
                                    0,              // first column
                                    7               // last column
                            ));
                        }
                    }
                })
                .build();

        // 4. Write data
        WriteSheet writeSheet = EasyExcel.writerSheet("SMTDashboard基础数据").build();
        excelWriter.write(dataList, writeSheet);
        excelWriter.finish();
    }

    @PostMapping("/excel")
    public AjaxResult importctExcel(@RequestParam("file") MultipartFile file) throws IOException {
        // 1. 读取Excel数据
        List<Smtdashboard> dataList = EasyExcel.read(file.getInputStream())
                .head(Smtdashboard.class)
                .sheet()
                .doReadSync();

        // 2. 数据校验和处理
        if (dataList.isEmpty()) {
            return error("导入数据为空");
        }

//        // 3. 业务处理（示例：保存到数据库）
       int size= smtTableService.batchSave(dataList);

        return success("成功导入 " + size + " 条数据");
    }

    @GetMapping("/template")
    public void exportTemplate(HttpServletResponse response) throws IOException {
        // 1. 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        String fileName = URLEncoder.encode("数据导入模板", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        // 2. 创建空数据列表（仅表头）
        List<Smtdashboard> dataList = Collections.emptyList();

        // 3. 导出模板
        EasyExcel.write(response.getOutputStream(), Smtdashboard.class)
                .registerWriteHandler(new HorizontalCellStyleStrategy(
                        createHeaderStyle(),  // 表头样式
                        new WriteCellStyle()  // 内容样式
                ))
                .sheet("导入模板")
                .doWrite(dataList);
    }

    // 创建表头样式
    private WriteCellStyle createHeaderStyle() {
        WriteCellStyle style = new WriteCellStyle();
        WriteFont font = new WriteFont();
        font.setFontHeightInPoints((short) 12);
        font.setBold(true);
        font.setColor(IndexedColors.WHITE.getIndex());
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
        style.setWriteFont(font);
        return style;
    }

}
